package com.ares.service.util;

import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;

public class ldap{

    static String ATTRIBUTE_FOR_USER = "sAMAccountName";

    public Attributes authenticateUser(String username, String password, String host, String dn){

        String returnedAtts[] ={ "sn", "givenName", "mail" };
        String searchFilter = "(&(objectClass=user)(" + ATTRIBUTE_FOR_USER + "=" + username + "))";
        
        SearchControls searchCtls = new SearchControls();
        searchCtls.setReturningAttributes(returnedAtts);
        
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = dn;
        Hashtable environment = new Hashtable();
        environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");                  

        environment.put(Context.PROVIDER_URL, "ldap://" + host + ":389");
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        
        environment.put(Context.SECURITY_PRINCIPAL, "HOCHSCHILD\\"+username);
        environment.put(Context.SECURITY_CREDENTIALS, password);
        LdapContext ctxGC = null;

        try{
            ctxGC = new InitialLdapContext(environment, null);
            NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
            while(answer.hasMoreElements()){
                SearchResult sr = (SearchResult)answer.next();
                Attributes attrs = sr.getAttributes();
                if(attrs != null){
                    return attrs;
                }
            }
        }catch(NamingException e){
            System.out.println("Just reporting error");
        }
        return null;
    }
}